import { NextRequest, NextResponse } from 'next/server';
import { UserModel } from '@/models/user';

// GET /api/profile/internships/[id] - 获取特定实习经历详情
export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 从请求头获取token并验证用户身份
    const authHeader = req.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { message: '未授权访问' },
        { status: 401 }
      );
    }
    
    const token = authHeader.split(' ')[1];
    
    // 解析JWT token
    let userId;
    try {
      const payload = JSON.parse(atob(token.split('.')[1]));
      userId = payload.id;
      
      if (!userId) {
        return NextResponse.json(
          { message: '无效的用户凭证' },
          { status: 401 }
        );
      }
    } catch (e) {
      console.error('解析token失败:', e);
      return NextResponse.json(
        { message: '无效的用户凭证' },
        { status: 401 }
      );
    }
    
    const internshipId = parseInt(params.id);
    
    if (isNaN(internshipId)) {
      return NextResponse.json(
        { message: '无效的实习经历ID' },
        { status: 400 }
      );
    }
    
    // 获取特定实习经历详情
    const internship = await UserModel.getInternshipById(internshipId, userId);
    
    if (!internship) {
      return NextResponse.json(
        { message: '实习经历不存在或无权访问' },
        { status: 404 }
      );
    }
    
    return NextResponse.json(
      internship,
      { status: 200 }
    );
  } catch (error: any) {
    console.error('获取实习经历详情时出错:', error);
    
    return NextResponse.json(
      { message: '获取实习经历详情失败', error: error.message },
      { status: 500 }
    );
  }
}

// PUT /api/profile/internships/[id] - 更新特定实习经历
export async function PUT(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 从请求头获取token并验证用户身份
    const authHeader = req.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { message: '未授权访问' },
        { status: 401 }
      );
    }
    
    const token = authHeader.split(' ')[1];
    
    // 解析JWT token
    let userId;
    try {
      const payload = JSON.parse(atob(token.split('.')[1]));
      userId = payload.id;
      
      if (!userId) {
        return NextResponse.json(
          { message: '无效的用户凭证' },
          { status: 401 }
        );
      }
    } catch (e) {
      console.error('解析token失败:', e);
      return NextResponse.json(
        { message: '无效的用户凭证' },
        { status: 401 }
      );
    }
    
    const internshipId = parseInt(params.id);
    
    if (isNaN(internshipId)) {
      return NextResponse.json(
        { message: '无效的实习经历ID' },
        { status: 400 }
      );
    }
    
    // 解析请求体
    const body = await req.json();
    
    // 验证必需字段
    if (!body.company || !body.position || !body.period) {
      return NextResponse.json(
        { message: '缺少必要字段' },
        { status: 400 }
      );
    }
    
    // 验证实习经历所有权
    const existingInternship = await UserModel.getInternshipById(internshipId, userId);
    
    if (!existingInternship) {
      return NextResponse.json(
        { message: '实习经历不存在或无权修改' },
        { status: 404 }
      );
    }
    
    // 准备更新数据
    const internshipData = {
      company: body.company,
      position: body.position,
      period: body.period,
      description: body.description || null
    };
    
    // 更新实习经历
    await UserModel.updateInternship(internshipId, userId, internshipData);
    
    // 获取更新后的实习经历详情
    const updatedInternship = await UserModel.getInternshipById(internshipId, userId);
    
    return NextResponse.json(
      updatedInternship,
      { status: 200 }
    );
  } catch (error: any) {
    console.error('更新实习经历时出错:', error);
    
    return NextResponse.json(
      { message: '更新实习经历失败', error: error.message },
      { status: 500 }
    );
  }
}

// DELETE /api/profile/internships/[id] - 删除特定实习经历
export async function DELETE(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 从请求头获取token并验证用户身份
    const authHeader = req.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { message: '未授权访问' },
        { status: 401 }
      );
    }
    
    const token = authHeader.split(' ')[1];
    
    // 解析JWT token
    let userId;
    try {
      const payload = JSON.parse(atob(token.split('.')[1]));
      userId = payload.id;
      
      if (!userId) {
        return NextResponse.json(
          { message: '无效的用户凭证' },
          { status: 401 }
        );
      }
    } catch (e) {
      console.error('解析token失败:', e);
      return NextResponse.json(
        { message: '无效的用户凭证' },
        { status: 401 }
      );
    }
    
    const internshipId = parseInt(params.id);
    
    if (isNaN(internshipId)) {
      return NextResponse.json(
        { message: '无效的实习经历ID' },
        { status: 400 }
      );
    }
    
    // 验证实习经历所有权
    const existingInternship = await UserModel.getInternshipById(internshipId, userId);
    
    if (!existingInternship) {
      return NextResponse.json(
        { message: '实习经历不存在或无权删除' },
        { status: 404 }
      );
    }
    
    // 删除实习经历
    await UserModel.deleteInternship(internshipId, userId);
    
    return NextResponse.json(
      { message: '实习经历删除成功' },
      { status: 200 }
    );
  } catch (error: any) {
    console.error('删除实习经历时出错:', error);
    
    return NextResponse.json(
      { message: '删除实习经历失败', error: error.message },
      { status: 500 }
    );
  }
} 